package com.heba.greenmulu.diary;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.viewpager.widget.ViewPager;
import android.util.Log;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.heba.adapter.diary.DiaryPhotoEditPagerAdapter;
import com.heba.bean.diary.ItemUploadPhotoObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.greenmulu.BaseActivity;
import com.heba.greenmulu.R;
import com.heba.utils.ImageTools;
import com.heba.utils.ToastShow;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 拍照或者相册选择后进入的viewpager编辑页面
 * Created by jason on 2020/4/14.
 */
public class ItemDiaryPhotoEditActivity extends BaseActivity {

    //裁剪图片比例
    public static final int RATIO_X = 1;
    public static final int RATIO_Y = 1;
    public static final float SCALE = 1f;

    private ViewPager viewPager;

    private DiaryPhotoEditPagerAdapter adapter;

    private List<ItemUploadPhotoObject> list;   //已保存的图片列表

    private int type;   //用于判断是拍照 还是相册进来 type=1是拍照  type=2是相册
    private List<String> paths;  //相册选择传递的文件路径
    private String path;   //拍照传递的文件路径

    private List<ItemUploadPhotoObject> tempList;   //待编辑的图片列表

    //需要编辑的图片的位置
    private int photoPostion;
    private String photoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary_photo_edit);
        /**
         * 设置狀態欄顏色
         */
        ImmersionBar.with(this)
                .statusBarColor(R.color.colorTextLogIn)
                .init();

        initTopbar();
        findViewById();
        initView();
        initViewpager();
    }

    @Override
    protected void findViewById() {
        viewPager = findViewById(R.id.viewPager);
    }

    @Override
    protected void initView() {
        tempList = new ArrayList<>();

        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            type = bundle.getInt(CommonConfig.TYPE, 0);
            path = bundle.getString(CommonConfig.DIARY_PATH, "");
            paths = (List<String>) bundle.getSerializable(CommonConfig.DIARY_PATH_LIST);
            list = (List<ItemUploadPhotoObject>) bundle.getSerializable(CommonConfig.DIARY_IMAGE_LIST);
        }

        /**
         * 用集合迭代器删除 防止ConcurrentModificationException异常抛出
         * 移除默认的上传icon
         */
        Iterator<ItemUploadPhotoObject> iterator = list.iterator();
        while (iterator.hasNext()) {
            ItemUploadPhotoObject object = iterator.next();
            if (object.getImageType() == ItemUploadPhotoObject.SHOW_IMAGE_ICON) {
                iterator.remove();
            }
        }

        /**
         * 根据type判断是编辑拍照还是相册照片
         */
        switch (type) {
            case CommonConfig.TYPE_TAKE_PHOTO:
                //拍照处理
                ItemUploadPhotoObject object = new ItemUploadPhotoObject();
                object.setImageType(ItemUploadPhotoObject.SHOW_IMAGE_PATH);
                object.setPhotoPath(path);
                tempList.add(object);
                break;
            case CommonConfig.TYPE_ALBUM:
                //相册处理
                for (int i = 0; i < paths.size(); i++) {
                    ItemUploadPhotoObject object1 = new ItemUploadPhotoObject();
                    object1.setImageType(ItemUploadPhotoObject.SHOW_IMAGE_PATH);
                    object1.setPhotoPath(paths.get(i));
                    tempList.add(object1);
                }
                break;
            case CommonConfig.TYPE_EDIT:
                //编辑图片
                for (int i = 0; i < paths.size(); i++) {
                    ItemUploadPhotoObject object1 = new ItemUploadPhotoObject();
                    object1.setImageType(ItemUploadPhotoObject.SHOW_IMAGE_PATH);
                    object1.setPhotoPath(paths.get(i));
                    tempList.add(object1);
                }
            default:
                break;
        }

        /**
         * 如果只有一張圖片，直接進入裁剪頁面
         */
        if (tempList != null && tempList.size() == 1) {
            photoPath = startUCrop(tempList.get(0).getPhotoPath());
            photoPostion = 0;
        }

        /**
         * 判断图片比例，保存图片
         * 通过Eventbus刷新图片数据
         */
        txt_right.setOnClickListener(v -> {
            for (ItemUploadPhotoObject object : tempList) {
                /**
                 * 先判断图片比例
                 */
                if (getImageScale(object) != SCALE) {
                    ToastShow.displayToast(ItemDiaryPhotoEditActivity.this, getResources().getString(R.string.diary_photo_edit_tips));
                    return;
                }
            }

            /**
             * 添加图片数据
             */
            if (type == CommonConfig.TYPE_EDIT) {
                list.clear();
                list.addAll(tempList);
            } else {
                list.addAll(list.size(), tempList);
            }

            /**
             * Eventbus刷新图片数据
             */
            MessageEvent event = new MessageEvent();
            event.setEvent(CommonConfig.EVENT_UPLOAD_PHOTO_LIST);
            event.setUploadPhotoObjectList(list);
            EventBus.getDefault().post(event);
            finishActivity();
        });
    }

    /**
     * initViewpager
     */
    private void initViewpager() {
        txt_title.setText("1/" + tempList.size());
        adapter = new DiaryPhotoEditPagerAdapter(this, tempList);
        viewPager.setAdapter(adapter);

        /**
         * 图片编辑回调监听
         */
        adapter.setonDiaryPhotoEditListener(new DiaryPhotoEditPagerAdapter.DiaryPhotoEditListener() {
            @Override
            public void onPhotoEdit(int position, String url) {
                //编辑图片(裁剪和旋转)
                photoPath = startUCrop(url);
                photoPostion = position;
            }
        });

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                txt_title.setText((i + 1) + "/" + tempList.size());
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    /**
     * 裁剪图片
     */
    private String startUCrop(String url) {
        //裁剪后保存的目标路径
        File tempFile = ImageTools.createFile(ImageTools.getUploadPathFolder(), ImageTools.getFileName());
        Uri destinationUri = Uri.fromFile(tempFile);
        //操作的原图路径
        Uri imageUri = Uri.fromFile(new File(url));
        UCrop uCrop = UCrop.of(imageUri, destinationUri);
        //设置裁剪属性
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.NONE, UCropActivity.SCALE);
        //设置保存图片的格式
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);
        //是否隐藏底部容器，默认显示
//        options.setHideBottomControls(true);
        //设置toolbar颜色
//        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorTextLogIn));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorTextLogIn));
        //是否能调整裁剪框
//        options.setFreeStyleCropEnabled(true);
        //设置裁剪图片的宽高比
        uCrop.withAspectRatio(RATIO_X, RATIO_Y);
        //UCrop配置
        uCrop.withOptions(options);
        uCrop.start(this);
        return tempFile.getAbsolutePath();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == UCrop.REQUEST_CROP) {
                handleCropResult(data);
            }
        }
        if (resultCode == UCrop.RESULT_ERROR) {
            handleCropError(data);
        }
    }


    /**
     * 裁剪处理完成
     *
     * @param result
     */
    private void handleCropResult(@NonNull Intent result) {
        final Uri resultUri = UCrop.getOutput(result);
        if (resultUri != null) {
            /**
             * 刷新viewpager列表
             */
            tempList.get(photoPostion).setPhotoPath(photoPath);   //保存裁剪的图片路径
            //刷新列表
            adapter.setList(tempList);
            viewPager.setCurrentItem(photoPostion);
        } else {
            Toast.makeText(ItemDiaryPhotoEditActivity.this, "找不到圖片資源", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 裁剪处理失败
     *
     * @param result
     */
    private void handleCropError(@NonNull Intent result) {
        final Throwable cropError = UCrop.getError(result);
        if (cropError != null) {
            Log.e(TAG, "handleCropError: ", cropError);
            Toast.makeText(ItemDiaryPhotoEditActivity.this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(ItemDiaryPhotoEditActivity.this, "unexpected_error", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取图片比例
     *
     * @param object
     * @return
     */
    private double getImageScale(ItemUploadPhotoObject object) {
        double scale;
        //获取图片实际宽高
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(object.getPhotoPath(), options);
        int imageWidth = options.outWidth;
        int imageHeight = options.outHeight;

        //计算图片旋转角度
        int orientation = ImageTools.getImageOrientation(object.getPhotoPath());
        switch (orientation) {
            //判断图片是否被旋转
            case ExifInterface.ORIENTATION_ROTATE_90:
            case ExifInterface.ORIENTATION_ROTATE_270:
                object.setImageWidth(imageHeight);
                object.setImageHeight(imageWidth);
//                scale = (float) imageWidth / imageHeight;
                scale = new BigDecimal((float) imageHeight / imageWidth).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                break;
            default:
                object.setImageWidth(imageWidth);
                object.setImageHeight(imageHeight);
//                scale = (float) imageHeight / imageWidth;
                scale = new BigDecimal((float) imageWidth / imageHeight).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }

        return scale;
    }

}
